package com.corpgovernment.organization.dataloader.db;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.corpgovernment.api.organization.model.bookingrelation.BookingRange;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.organization.entity.db.MbFreshPassenger;
import com.corpgovernment.organization.mapper.MbFreshPassengerMapper;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.context.PageContext;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.IPage;

import lombok.extern.slf4j.Slf4j;

import java.util.Comparator;
import java.util.Objects;

@Component
@Slf4j
public class MbFreshPassengerLoader {


	@Autowired
	private MbFreshPassengerMapper freshPassengerMapper;
	@Autowired
	private OrganizationApollo organizationApollo;

	/**
	 * 根据代订范围和员工信息查询
	 *
	 * @param bookingOrgIds
	 * @param uid
	 * @param orgId
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public List<MbFreshPassenger> pageByBookingOrgIds(List<String> bookingOrgIds, List<BookingRange.BookingUser> bookingUsers, String uid, String orgId, Integer pageNum, Integer pageSize) {
		IPage<Object> page = PageContext.startPage(pageNum, pageSize);
		log.info("selectByBookingOrgIdsAndFreshPassengerIds request, bookingOrgIds:{}, bookingUsers:{}, orgId:{}", JsonUtils.toJsonString(bookingOrgIds), JsonUtils.toJsonString(bookingUsers), orgId);
		List<MbFreshPassenger> mbFreshPassengers = freshPassengerMapper.selectByBookingOrgIdsAndFreshPassengerIds(bookingOrgIds, bookingUsers, null, uid, orgId);
		log.info("selectByBookingOrgIdsAndFreshPassengerIds result:{}", JsonUtils.toJsonString(mbFreshPassengers));
		MbFreshPassenger mbFreshPassenger = mbFreshPassengers.stream().filter(m-> StrUtil.isNotBlank(m.getEmployeeUid()) && m.getEmployeeUid().equals(uid)).findFirst().orElse(null);
		if(ObjectUtil.isNotNull(mbFreshPassenger)){
			mbFreshPassengers.remove(mbFreshPassenger);
			mbFreshPassengers.add(0,mbFreshPassenger);
		}
		if (pageNum > page.getPages()){
			return new ArrayList<>();
		}
		return sortByFreshTime(mbFreshPassengers);
	}

    private List<MbFreshPassenger> sortByFreshTime(List<MbFreshPassenger> freshPassengerList) {
	    if (CollectionUtils.isEmpty(freshPassengerList)){
            return freshPassengerList;
        }
        List<MbFreshPassenger> employeeList = freshPassengerList.stream().filter(e -> StringUtils.isNotBlank(e.getEmployeeUid())).collect(Collectors.toList());
        List<MbFreshPassenger> nonEmployeeList = freshPassengerList.stream().filter(e -> Objects.nonNull(e.getNonEmployeeUid())).collect(Collectors.toList());
        List<MbFreshPassenger> sortedEmployeeList = new ArrayList<>();
        List<MbFreshPassenger> sortedNonEmployeeList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(employeeList)) {
            sortedEmployeeList = employeeList.stream().sorted(Comparator.comparing(MbFreshPassenger::getFreshTime).reversed()).collect(Collectors.toList());
        }
        if (CollectionUtils.isNotEmpty(nonEmployeeList)) {
            sortedNonEmployeeList = nonEmployeeList.stream().sorted(Comparator.comparing(MbFreshPassenger::getFreshTime).reversed()).collect(Collectors.toList());
        }
        ArrayList<MbFreshPassenger> result = new ArrayList<>();
        result.addAll(sortedEmployeeList);
        result.addAll(sortedNonEmployeeList);
        return result;
    }

    /**
	 * 根据代订范围和员工信息查询
	 *
	 * @param bookingOrgIds
	 * @param freshPassengerIds
	 * @param uid
	 * @param orgId
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public List<MbFreshPassenger> pageByBookingOrgIdsAndFreshPassengerIds(List<String> bookingOrgIds, List<BookingRange.BookingUser> bookingUsers, List<Long> freshPassengerIds, String uid, String orgId, Integer pageNum, Integer pageSize) {
		IPage<Object> page = PageContext.startPage(pageNum, pageSize);
		List<MbFreshPassenger> mbFreshPassengers = freshPassengerMapper.selectByBookingOrgIdsAndFreshPassengerIds(bookingOrgIds, bookingUsers, freshPassengerIds, uid, orgId);
		MbFreshPassenger mbFreshPassenger = mbFreshPassengers.stream().filter(m-> StrUtil.isNotBlank(m.getEmployeeUid()) && m.getEmployeeUid().equals(uid)).findFirst().orElse(null);
		if(ObjectUtil.isNotNull(mbFreshPassenger)){
			mbFreshPassengers.remove(mbFreshPassenger);
			mbFreshPassengers.add(0,mbFreshPassenger);
		}
		if (pageNum > page.getPages()){
			return new ArrayList<>();
		}
		return mbFreshPassengers;
	}

	public List<Long> queryLikeName(String name, boolean needEmployee) {
		List<MbFreshPassenger> freshPassengerList = freshPassengerMapper.queryAllName();
		log.info("查询条件：名称：{}，员工：{}，查询到的结果：{}", name, needEmployee, JsonUtils.toJsonString(freshPassengerList));
		List<Long> freshPassengerId = freshPassengerList.stream()
				.filter(e -> StringUtils.contains(e.getName(), name) || StringUtils.contains(e.getEnName(), name))
				.filter(e -> !needEmployee || StringUtils.isNotBlank(e.getEmployeeUid()))
				.map(MbFreshPassenger::getId).collect(Collectors.toList());
		log.info("获取到的出行人的id：{}", JsonUtils.toJsonString(freshPassengerId));
		return freshPassengerId;
	}

	public List<MbFreshPassenger> findByNonEmployeeIds(List<Long> nonEmployeeIds) {
		return freshPassengerMapper.findByNonEmployeeIds(nonEmployeeIds);

	}

	public List<MbFreshPassenger> findByEmployeeIds(List<String> employeeIds) {
		return freshPassengerMapper.findByEmployeeIds(employeeIds);
	}

	public List<Long> queryByName(String name, boolean needEmployee) {
		return freshPassengerMapper.findByName(name, needEmployee);
	}

	public List<MbFreshPassenger> pageEmployeeByBookingOrgIds(List<String> bookingOrgIds, List<BookingRange.BookingUser> bookingUsers, String uid, Integer pageNum, Integer pageSize, String orgId) {
		IPage<Object> page = PageContext.startPage(pageNum, pageSize);
		List<MbFreshPassenger> mbFreshPassengers = freshPassengerMapper.selectEmployeeByBookingOrgIdsAndFreshPassengerIds(bookingOrgIds, bookingUsers, null, uid, orgId);
		if (pageNum > page.getPages()){
			return new ArrayList<>();
		}
		return mbFreshPassengers;
	}

	public List<MbFreshPassenger> pageEmployeeByBookingOrgIdsAndName(List<String> bookingOrgIds, List<BookingRange.BookingUser> bookingUsers, List<Long> freshPassengerIds, String uid, Integer pageNum, Integer pageSize, String orgId) {
		IPage<Object> page = PageContext.startPage(pageNum, pageSize);
		List<MbFreshPassenger> mbFreshPassengers = freshPassengerMapper.selectEmployeeByBookingOrgIdsAndFreshPassengerIds(bookingOrgIds, bookingUsers, freshPassengerIds, uid, orgId);
		if (pageNum > page.getPages()){
			return new ArrayList<>();
		}
		return mbFreshPassengers;
	}

	public List<MbFreshPassenger> pageByUidAndOrgId(String uid, String orgId, Integer pageNum, Integer pageSize) {
		IPage<Object> page = PageContext.startPage(pageNum, pageSize);
		List<MbFreshPassenger> mbFreshPassengers = freshPassengerMapper.selectByUidAndOrgIdAndFreshPassengerIds(uid, orgId, null);
		if (pageNum > page.getPages()){
			return new ArrayList<>();
		}
		return mbFreshPassengers;
	}

	public List<MbFreshPassenger> pageByUidAndOrgIdAndFreshPassengerIds(List<Long> freshPassengerIds, String uid, String orgId, Integer pageNum, Integer pageSize) {
		IPage<Object> page = PageContext.startPage(pageNum, pageSize);
		List<MbFreshPassenger> mbFreshPassengers = freshPassengerMapper.selectByUidAndOrgIdAndFreshPassengerIds(uid, orgId, freshPassengerIds);
		if (pageNum > page.getPages()){
			return new ArrayList<>();
		}
		return mbFreshPassengers;
	}
}
